<template>
  <view class="product-manage">
    <view class="search-bar">
      <input 
        type="text" 
        v-model="searchKeyword" 
        placeholder="搜索商品名称" 
        @input="handleSearch"
      />
      <button class="add-btn" @click="showAddJsonModal = true">添加商品</button>
    </view>
    
    <view class="product-table">
      <view class="table-header">
        <view class="th">商品图片</view>
        <view class="th">商品名称</view>
        <view class="th">价格</view>
        <view class="th">详情页图片</view>
        <view class="th">状态</view>
        <view class="th">操作</view>
      </view>
      <view class="table-body">
        <view v-if="productList.length === 0" class="empty-data">
          <text class="empty-text">暂无商品数据</text>
        </view>
        <view v-else v-for="product in productList" :key="product._id" class="table-row">
          <view class="td">
            <image 
              :src="url('sp', product.id-1, 'png')" 
              mode="aspectFill" 
              class="product-image"
            />
          </view>
          <view class="td">{{ product.name }}</view>
          <view class="td">¥{{ product.price }}</view>
          <view class="td">
            <image 
              v-if="product.detailImage" 
              :src="product.detailImage" 
              mode="aspectFill" 
              class="detail-image"
              @click="previewDetailImage(product)"
            />
            <image 
              v-else-if="getDetailImagePath(product)" 
              :src="getDetailImagePath(product)" 
              mode="aspectFill" 
              class="detail-image"
              @click="previewDetailImage(product)"
            />
            <text v-else class="no-image">暂无图片</text>
          </view>
          <view class="td">
            <switch 
              :checked="product.status === 1" 
              @change="handleStatusChange(product)"
            />
          </view>
          <view class="td">
            <text class="action-btn" @click="handleEdit(product)">编辑</text>
            <text class="action-btn delete" @click="handleDelete(product)">删除</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- JSON添加/编辑商品弹窗 -->
    <uni-popup ref="jsonPopup" type="center">
      <view class="popup-content json-popup">
        <view class="popup-title">通过JSON添加商品</view>
        <view class="form-item">
          <text class="label">JSON数据</text>
          <textarea 
            v-model="jsonInput" 
            placeholder="请输入有效的JSON格式数据"
            class="json-textarea"
          ></textarea>
        </view>
        <view class="json-tips">
          <text>提示: JSON格式必须包含以下字段:</text>
          <text>name (String): 商品名称</text>
          <text>price (Number): 商品价格</text>
          <text>description (String): 商品描述</text>
          <text>image (String, 可选): 商品图片URL</text>
          <text>detailImage (String, 可选): 详情页图片URL</text>
          <text>注意: 不设置detailImage时，系统将根据商品ID自动生成详情页图片</text>
        </view>
        <view class="btn-group">
          <button @click="closeJsonPopup">取消</button>
          <button @click="handleJsonSubmit">确定</button>
        </view>
      </view>
    </uni-popup>
    
    <!-- 常规编辑商品弹窗 -->
    <uni-popup ref="productPopup" type="center">
      <view class="popup-content">
        <view class="popup-title">{{ isEdit ? '编辑商品' : '添加商品' }}</view>
        <view class="form-item">
          <text class="label">商品名称</text>
          <input type="text" v-model="currentProduct.name" />
        </view>
        <view class="form-item">
          <text class="label">商品价格</text>
          <input type="number" v-model="currentProduct.price" />
        </view>
        <view class="form-item">
          <text class="label">商品图片</text>
          <view class="upload-box" @click="chooseImage('main')">
            <image 
              v-if="currentProduct.image" 
              :src="url('sp', currentProduct.id, 'png')" 
              mode="aspectFill" 
              class="preview-image"
            />
            <view v-else class="upload-placeholder">
              <text class="iconfont icon-upload"></text>
              <text>点击上传图片</text>
            </view>
          </view>
        </view>
        <view class="form-item">
          <text class="label">详情页图片</text>
          <view class="upload-box" @click="chooseImage('detail')">
            <image 
              v-if="currentProduct.detailImage" 
              :src="currentProduct.detailImage" 
              mode="aspectFill" 
              class="preview-image"
            />
            <image 
              v-else-if="getDetailImagePath(currentProduct)" 
              :src="getDetailImagePath(currentProduct)" 
              mode="aspectFill" 
              class="preview-image"
            />
            <view v-else class="upload-placeholder">
              <text class="iconfont icon-upload"></text>
              <text>点击上传图片</text>
            </view>
          </view>
          <view class="detail-image-options" v-if="isEdit && currentProduct.id">
            <text class="option-text">或使用系统生成的详情页图片:</text>
            <button class="use-system-image" @click.stop="useSystemImage">使用系统图片</button>
          </view>
        </view>
        <view class="form-item">
          <text class="label">商品描述</text>
          <textarea 
            v-model="currentProduct.description" 
            placeholder="请输入商品描述"
          ></textarea>
        </view>
        <view class="btn-group">
          <button @click="handleCancel">取消</button>
          <button @click="handleSubmit">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
const url = $url
const searchKeyword = ref('')
const productList = ref([])
const showAddJsonModal = ref(false)
const isEdit = ref(false)
const jsonInput = ref('')
const currentProduct = ref({
  name: '',
  price: '',
  detailImage: '',
  image: '',
  description: ''
})
const productPopup = ref(null)
const jsonPopup = ref(null)

// 获取详情页图片路径
const getDetailImagePath = (product) => {
  if (product.detailImage) {
    // 如果已有详情页图片，直接返回
    return product.detailImage;
  }
  
  // 否则根据商品ID生成详情页图片路径
  if (!product || !product.id) return '';
  
  const productIndex = product.id - 1;
  return url('sp', productIndex, 'png');
}

// 预览详情页图片
const previewDetailImage = (product) => {
  const imagePath = getDetailImagePath(product);
  if (!imagePath) return;
  
  uni.previewImage({
    urls: [imagePath],
    current: 0
  });
}

// 获取商品列表
const fetchProductList = async () => {
  try {
    uni.showLoading({
      title: '加载中...'
    })
    
    const res = await uniCloud.callFunction({
      name: 'alldata',
      data: {
        body: JSON.stringify({
          action: 'getProductList',
          keyword: searchKeyword.value,
          page: 1,
          pageSize: 50
        })
      }
    })
    
    uni.hideLoading()
    
    if (res.result && res.result.code === 0) {
      productList.value = res.result.data || []
      console.log('获取到商品数据:', productList.value)
    } else {
      uni.showToast({
        title: res.result?.message || '获取商品列表失败',
        icon: 'none'
      })
      console.error('获取商品列表失败:', res.result)
    }
  } catch (error) {
    uni.hideLoading()
    console.error('获取商品列表失败:', error)
    uni.showToast({
      title: '获取商品列表失败',
      icon: 'none'
    })
  }
}

// 搜索处理
const handleSearch = () => {
  fetchProductList()
}

// 预览图片
const previewImage = (url) => {
  if (!url) return
  uni.previewImage({
    urls: [url]
  })
}

// 修改商品状态
const handleStatusChange = async (product) => {
  try {
    uni.showLoading({
      title: '更新中...'
    })
    
    const res = await uniCloud.callFunction({
      name: 'alldata',
      data: {
        body: JSON.stringify({
          action: 'updateProduct',
          productId: product._id,
          data: {
            status: product.status === 1 ? 0 : 1
          }
        })
      }
    })
    
    uni.hideLoading()
    
    if (res.result && res.result.code === 0) {
      uni.showToast({
        title: '状态更新成功',
        icon: 'success'
      })
      fetchProductList()
    } else {
      uni.showToast({
        title: res.result?.message || '状态更新失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('更新商品状态失败:', error)
    uni.showToast({
      title: '状态更新失败',
      icon: 'none'
    })
  }
}

// 选择图片
const chooseImage = (type = 'main') => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      if (type === 'main') {
        currentProduct.value.image = res.tempFilePaths[0]
      } else if (type === 'detail') {
        currentProduct.value.detailImage = res.tempFilePaths[0]
      }
    }
  })
}

// 使用系统生成的详情页图片
const useSystemImage = () => {
  // 清空已上传的详情页图片
  currentProduct.value.detailImage = '';
  // 使用系统生成的详情页图片会使用getDetailImagePath方法生成
  uni.showToast({
    title: '已使用系统图片',
    icon: 'success'
  });
}

// 编辑商品
const handleEdit = (product) => {
  isEdit.value = true
  currentProduct.value = { ...product }
  productPopup.value.open()
}

// 关闭JSON弹窗
const closeJsonPopup = () => {
  jsonPopup.value.close()
  jsonInput.value = ''
}

// 处理JSON提交
const handleJsonSubmit = async () => {
  try {
    // 验证JSON格式
    let productData
    try {
      productData = JSON.parse(jsonInput.value)
    } catch (e) {
      uni.showToast({
        title: 'JSON格式无效',
        icon: 'none'
      })
      return
    }
    
    // 验证必要字段
    if (!productData.name) {
      uni.showToast({
        title: '缺少name字段',
        icon: 'none'
      })
      return
    }
    
    if (productData.price === undefined || isNaN(Number(productData.price))) {
      uni.showToast({
        title: '缺少有效的price字段',
        icon: 'none'
      })
      return
    }
    
    // 添加默认值
    productData.status = productData.status || 1
    
    // 检查detailImage字段格式
    if (productData.detailImage && typeof productData.detailImage !== 'string') {
      uni.showToast({
        title: 'detailImage必须是字符串格式',
        icon: 'none'
      })
      return
    }
    
    uni.showLoading({
      title: '添加中...'
    })
    
    const res = await uniCloud.callFunction({
      name: 'alldata',
      data: {
        body: JSON.stringify({
          action: 'addProduct',
          data: productData
        })
      }
    })
    
    uni.hideLoading()
    
    if (res.result && res.result.code === 0) {
      uni.showToast({
        title: '添加成功',
        icon: 'success'
      })
      closeJsonPopup()
      fetchProductList()
    } else {
      uni.showToast({
        title: res.result?.message || '添加失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('添加商品失败:', error)
    uni.showToast({
      title: '添加失败',
      icon: 'none'
    })
  }
}

// 删除商品
const handleDelete = async (product) => {
  try {
    // 确认删除
    uni.showModal({
      title: '确认删除',
      content: `确定要删除商品"${product.name}"吗？`,
      success: async (res) => {
        if (res.confirm) {
          uni.showLoading({
            title: '删除中...'
          })
          
          const result = await uniCloud.callFunction({
            name: 'alldata',
            data: {
              body: JSON.stringify({
                action: 'deleteProduct',
                productId: product._id
              })
            }
          })
          
          uni.hideLoading()
          
          if (result.result && result.result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            fetchProductList()
          } else {
            uni.showToast({
              title: result.result?.message || '删除失败',
              icon: 'none'
            })
          }
        }
      }
    })
  } catch (error) {
    uni.hideLoading()
    console.error('删除商品失败:', error)
    uni.showToast({
      title: '删除失败',
      icon: 'none'
    })
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    if (!currentProduct.value.name) {
      uni.showToast({
        title: '请输入商品名称',
        icon: 'none'
      })
      return
    }
    
    if (!currentProduct.value.price) {
      uni.showToast({
        title: '请输入商品价格',
        icon: 'none'
      })
      return
    }
    
    uni.showLoading({
      title: isEdit.value ? '更新中...' : '添加中...'
    })
    
    // 准备提交数据
    const submitData = {
      name: currentProduct.value.name,
      price: Number(currentProduct.value.price),
      image: currentProduct.value.image,
      description: currentProduct.value.description,
      status: currentProduct.value.status || 1
    }
    
    // 如果有自定义的详情页图片，则使用它
    if (currentProduct.value.detailImage) {
      submitData.detailImage = currentProduct.value.detailImage
    }
    
    const res = await uniCloud.callFunction({
      name: 'alldata',
      data: {
        body: JSON.stringify({
          action: isEdit.value ? 'updateProduct' : 'addProduct',
          productId: isEdit.value ? currentProduct.value._id : undefined,
          data: submitData
        })
      }
    })
    
    uni.hideLoading()
    
    if (res.result && res.result.code === 0) {
      uni.showToast({
        title: `${isEdit.value ? '更新' : '添加'}成功`,
        icon: 'success'
      })
      productPopup.value.close()
      fetchProductList()
      resetForm()
    } else {
      uni.showToast({
        title: res.result?.message || `${isEdit.value ? '更新' : '添加'}失败`,
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error(`${isEdit.value ? '更新' : '添加'}商品失败:`, error)
    uni.showToast({
      title: `${isEdit.value ? '更新' : '添加'}失败`,
      icon: 'none'
    })
  }
}

// 取消
const handleCancel = () => {
  productPopup.value.close()
  resetForm()
}

// 重置表单
const resetForm = () => {
  isEdit.value = false
  currentProduct.value = {
    name: '',
    price: '',
    detailImage: '',
    image: '',
    description: ''
  }
}

onMounted(() => {
  fetchProductList()
})
</script>

<style lang="scss" scoped>
.product-manage {
  padding: 20rpx;
  
  .search-bar {
    display: flex;
    margin-bottom: 30rpx;
    
    input {
      flex: 1;
      height: 80rpx;
      border: 1px solid #ddd;
      border-radius: 10rpx;
      padding: 0 20rpx;
      margin-right: 20rpx;
    }
    
    .add-btn {
      width: 160rpx;
      height: 80rpx;
      background-color: #1890ff;
      color: #fff;
      border-radius: 10rpx;
    }
  }
  
  .product-table {
    background-color: #fff;
    border-radius: 10rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .table-header {
      display: flex;
      background-color: #fafafa;
      border-bottom: 1px solid #f0f0f0;
      
      .th {
        flex: 1;
        padding: 20rpx;
        text-align: center;
        font-weight: bold;
      }
    }
    
    .table-body {
      .empty-data {
        padding: 100rpx 0;
        text-align: center;
        
        .empty-text {
          color: #999;
          font-size: 28rpx;
        }
      }
      
      .table-row {
        display: flex;
        border-bottom: 1px solid #f0f0f0;
        
        &:hover {
          background-color: #f9f9f9;
        }
        
        .td {
          flex: 1;
          padding: 20rpx;
          text-align: center;
          display: flex;
          align-items: center;
          justify-content: center;
          
          .product-image, .detail-image {
            width: 100rpx;
            height: 100rpx;
            border-radius: 10rpx;
            object-fit: cover;
          }
          
          .detail-image {
            width: 120rpx;
            height: 120rpx;
            border-radius: 10rpx;
            object-fit: cover;
            cursor: pointer;
            border: 1px solid #eee;
            transition: all 0.3s;
            
            &:hover {
              transform: scale(1.05);
              box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
            }
          }
          
          .no-image {
            color: #999;
            font-size: 24rpx;
          }
          
          .action-btn {
            color: #1890ff;
            margin: 0 10rpx;
            cursor: pointer;
            
            &.delete {
              color: #ff4d4f;
            }
          }
        }
      }
    }
  }
  
  .popup-content {
    width: 600rpx;
    padding: 30rpx;
    background-color: #fff;
    border-radius: 10rpx;
    
    &.json-popup {
      width: 700rpx;
    }
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      margin-bottom: 30rpx;
      text-align: center;
    }
    
    .json-tips {
      margin-bottom: 20rpx;
      font-size: 24rpx;
      color: #666;
      
      text {
        display: block;
        line-height: 1.5;
      }
    }
    
    .json-textarea {
      height: 360rpx;
      font-family: monospace;
    }
    
    .form-item {
      margin-bottom: 20rpx;
      
      .label {
        display: block;
        margin-bottom: 10rpx;
        color: #333;
      }
      
      input, textarea {
        width: 100%;
        border: 1px solid #ddd;
        border-radius: 10rpx;
        padding: 10rpx 20rpx;
      }
      
      textarea {
        height: 200rpx;
      }
      
      .upload-box {
        width: 200rpx;
        height: 200rpx;
        border: 1px dashed #ddd;
        border-radius: 10rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        
        .preview-image {
          width: 100%;
          height: 100%;
          border-radius: 10rpx;
          object-fit: cover;
        }
        
        .upload-placeholder {
          text-align: center;
          
          .iconfont {
            font-size: 48rpx;
            color: #999;
          }
          
          text {
            display: block;
            font-size: 24rpx;
            color: #999;
            margin-top: 10rpx;
          }
        }
      }
    }
    
    .btn-group {
      display: flex;
      justify-content: flex-end;
      margin-top: 30rpx;
      
      button {
        width: 160rpx;
        height: 80rpx;
        margin-left: 20rpx;
        
        &:first-child {
          background-color: #f5f5f5;
          color: #666;
        }
        
        &:last-child {
          background-color: #1890ff;
          color: #fff;
        }
      }
    }
  }
}

.detail-image-options {
  margin-top: 20rpx;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  
  .option-text {
    font-size: 24rpx;
    color: #666;
    margin-right: 20rpx;
    margin-bottom: 10rpx;
  }
  
  .use-system-image {
    font-size: 24rpx;
    padding: 8rpx 20rpx;
    background-color: #f5f5f5;
    border: 1px solid #ddd;
    color: #333;
    border-radius: 6rpx;
    height: auto;
    line-height: 1.5;
    
    &:hover {
      background-color: #e0e0e0;
    }
  }
}
</style> 